package com.weixing.mall.provider.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.core.properties.WeiXingProperties;
import com.weixing.mall.core.support.ImageService;
import com.weixing.mall.core.support.imgsearch.ImgSearchAddDto;
import com.weixing.mall.provider.api.erp.query.SkuQuery;
import com.weixing.mall.provider.api.erp.vo.ResultSkuInfoVo;
import com.weixing.mall.provider.api.model.query.ActGoodsQuery;
import com.weixing.mall.provider.api.model.query.ErpGoodsQuery;
import com.weixing.mall.provider.api.model.vo.ActivityProductVo;
import com.weixing.mall.provider.api.model.vo.ErpProductVo;
import com.weixing.mall.provider.api.model.vo.GoodsPlaceVo;
import com.weixing.mall.provider.api.model.vo.ItemVo;
import com.weixing.mall.provider.erp.service.ErpService;
import com.weixing.mall.provider.mapper.*;
import com.weixing.mall.provider.model.domain.*;
import com.weixing.mall.provider.model.dto.*;
import com.weixing.mall.provider.model.query.ProductQuery;
import com.weixing.mall.provider.model.vo.GoodsSpecValueVo;
import com.weixing.mall.provider.model.vo.GoodsSpecVo;
import com.weixing.mall.provider.model.vo.ProductSpecVo;
import com.weixing.mall.provider.model.vo.SkuVo;
import com.weixing.mall.provider.service.IProductService;
import com.weixing.mall.util.ListUtil;
import com.weixing.mall.util.SKUUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品模块-货品表 服务实现类
 * </p>
 *
 * @author Small
 * @since 2019-11-20
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    private SpecServiceImpl SpecService;
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private GoodsSpecMapper goodsSpecMapper;
    @Autowired
    private GoodsSpecValueMapper goodsSpecValueMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private GoodsImgMapper goodsImgMapper;
    @Autowired
    private ErpService erpService;


    @Autowired
    private WeiXingProperties weiXingProperties;

    @Override
    public ProductSpecVo selectByGoodsId(Long goodsId) {

        List<GoodsSpecVo> specVoList = goodsSpecMapper.selectByGoodsId(goodsId);
        for (GoodsSpecVo goodsSpecVo : specVoList) {

//            List<GoodsSpecValueVo> specValueVos=goodsSpecValueMapper.selectBySpecIdGoodsId(goodsId,goodsSpecVo.getSpecId());
//            goodsSpecVo.setSpecValueVoList(specValueVos);

            String specValue = goodsSpecVo.getSpecValue();

//            List<GoodsSpecValueVo> specValueVos = (List<GoodsSpecValueVo>) JSON.parseObject(specValue);

            List<GoodsSpecValueVo> specValueVos = JSONObject.parseArray(specValue, GoodsSpecValueVo.class);
//            System.out.println(specValueVos.toString());
            goodsSpecVo.setSpecValueVoList(specValueVos);
        }

        List<ItemVo> productVos = productMapper.selectByGoodsId(goodsId);

        ProductSpecVo productSpecVo = new ProductSpecVo();
        productSpecVo.setGoodsSpecVoList(specVoList);
        productSpecVo.setProductVoList(productVos);
        System.out.println(productSpecVo.toString() + "----------");
        return productSpecVo;
    }

    @Override
    public void save(ProductSpecDto productSpecDto) {
        List<ProductDto> productDtoList = productSpecDto.getProductDtoList();
        //在进行添加
        Product product = new Product();
        Goods goods = goodsMapper.selectById(productSpecDto.getGoodsId());
        List<ImgSearchAddDto> imgSearchAddDtos = Lists.newArrayList();
        for (ProductDto productDto : productDtoList) {
            BeanUtils.copyProperties(productDto, product);
            //查询商品的价格
            ImgSearchAddDto dto = new ImgSearchAddDto();
            product.setSupplierName(goods.getSupplierName());
            product.setMarketPrice(goods.getMarketPrice());
            product.setDiscountPrice(goods.getDiscountPrice());
            product.setProductImg(productDto.getProductImg());
            product.setStatus(2);
            if (ObjectUtil.isNotEmpty(productDto) && StrUtil.isNotEmpty(productDto.getProductSkuDesp())) {
                String[] skuDesp = productDto.getProductSkuDesp().split(",");
                if (skuDesp.length == 2) {
                    product.setColor(SKUUtils.color2(productDto.getProductSkuDesp()));
                    product.setSize(SKUUtils.size2(productDto.getProductSkuDesp()));
                }
            }
            if (productDto.getId() == null) {
                ProductQuery query = new ProductQuery();
                query.setStyleNo(productDto.getStyleNo());
                query.setProductSkuDesp(productDto.getProductSkuDesp());
                query.setProductSn(productDto.getGoodsSn());
                List<ItemVo> productList = selectProduct(query);
                if (!(CollUtil.isNotEmpty(productList) && productList.size() != 0)) {
                    product.setProductSn(UUID.randomUUID().toString().replaceAll("-", ""));
                    productMapper.insert(product);
                }

            } else {
                productMapper.updateById(product);
            }
            dto.setImgUrl(GlobalConstant.IMG_PATH_URL + product.getProductImg());
            dto.setProductId(goods.getId().toString() + "," + product.getId());
            dto.setPicName(goods.getGoodsName() + "," + GlobalConstant.IMG_PATH_URL + product.getProductImg());
            dto.setStrAttr(goods.getDiscountPrice() + "," + goods.getMarketPrice());
            dto.setCustomContent(goods.getStyleNo());

            imgSearchAddDtos.add(dto);
            try {
                ImageService imageService = new ImageService();
                imageService.add(imgSearchAddDtos, weiXingProperties.getAli().getImg());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //删除未提交的内容  TODO 需要测试下
        List<Product> list = productMapper.selectList(new QueryWrapper<Product>().eq("goods_id", goods.getId()));
        for (int i = 0; i < list.size(); i++) {
            Product product1 = list.get(i);
            for (ProductDto productDto : productDtoList) {
                String skudesp = product1.getProductSkuDesp();
                String sku = productDto.getProductSkuDesp();
                if (skudesp.equals(sku)) {
                    list.remove(i);
                    i--;
                }
            }
        }
        if (list.size() > 0) {
            List<Long> ids = list.stream().map(Product::getId).collect(Collectors.toList());
            productMapper.delete(new QueryWrapper<Product>().in("id", ids));
        }
        List<GoodsSpecDto> specDtoList = productSpecDto.getSpecDtoList();
        goodsSpecMapper.deleteByGoodsId(productSpecDto.getGoodsId());
        goodsSpecValueMapper.deleteByGoodsId(productSpecDto.getGoodsId());
        GoodsSpec goodsSpec = new GoodsSpec();
        for (GoodsSpecDto goodsSpecDto : specDtoList) {
            BeanUtils.copyProperties(goodsSpecDto, goodsSpec);
            List<GoodsSpecValueDto> specValueDtoList = goodsSpecDto.getSpecValueDtoList();
            String specValue = JSON.toJSONString(specValueDtoList);
            goodsSpec.setSpecValue(specValue);
            goodsSpecMapper.insert(goodsSpec);
            GoodsSpecValue goodsSpecValue = new GoodsSpecValue();
            for (GoodsSpecValueDto goodsSpecValueDto : specValueDtoList) {
                BeanUtils.copyProperties(goodsSpecValueDto, goodsSpecValue);
                goodsSpecValue.setGoodsId(productSpecDto.getGoodsId());
                goodsSpecValue.setSpecId(goodsSpec.getSpecId());
                goodsSpecValueMapper.insert(goodsSpecValue);
            }
        }
    }

    @Override
    public List<ActivityProductVo> findActProductVoByIds(long[] productIds) {
        return productMapper.findActProductVoByIds(productIds);
    }

    @Override
    public List<ActivityProductVo> findActProductVo(ActGoodsQuery goodsQuery) {
        return productMapper.findActProductVo(goodsQuery);
    }

    @Override
    public IPage<ActivityProductVo> findActProductVo(Page page, ActGoodsQuery goodsQuery) {
        return productMapper.findActProductVo(page, goodsQuery);
    }

    @Override
    public IPage<ErpProductVo> getErpGoodsList(Page page, ErpGoodsQuery egq) {
        IPage<ErpProductVo> list = productMapper.getErpGoodsList(page, egq);
        if (list.getRecords().size() > 0) {
            //遍历调用ERP接口查询对应库存
            list.getRecords().forEach(erpProductVo -> {
                //查询ERP可用库存
                SkuQuery skuQuery = new SkuQuery();
                skuQuery.setPageindex(1);
                skuQuery.setPagesize(1);
                skuQuery.setStyleid(erpProductVo.getStyleNo());
                skuQuery.setSku(erpProductVo.getProductSn());
                skuQuery.setDepotid(GlobalConstant.ERP_DEPOT_ID);
                Result<ResultSkuInfoVo> result = erpService.selectDepotSkuStockByPage(skuQuery);
                if (result.isSuccess()
                        && ObjectUtil.isNotEmpty(result.getData())
                        && result.getData().getTotal() > 0) {
                    ResultSkuInfoVo resultVo = result.getData();
                    resultVo.getData().forEach(skuInfo -> {
                        erpProductVo.setStock(Integer.valueOf(skuInfo.getP_num()));
                    });
                } else {
                    erpProductVo.setStock(0);
                }
            });
        }
        return list;
    }

    @Override
    public ItemVo selectProduct(GoodsIdProductSkuDto goodsIdProductSkuDto) {
        return productMapper.selectProduct(goodsIdProductSkuDto);
    }

    @Override
    public List<ItemVo> selectProduct(ProductQuery productQuery) {
        return productMapper.selectProductList(productQuery);
    }

    @Override
    public IPage<ItemVo> selectProduct(Page page, ProductQuery productQuery) {
        return productMapper.selectProductList(page, productQuery);
    }

    @Override
    public ItemVo findProductVoByProductSn(String productSn) {
        return productMapper.findProductVoByProductSn(productSn);
    }

    @Override
    public Product selectByProductSn(String productSn) {
        Product product = baseMapper.selectOne(new QueryWrapper<Product>().eq("product_sn", productSn));
        return product;
    }

    @Override
    public IPage<ActivityProductVo> findProductVoByCreatedId(Page page, Long createdById) {
        return baseMapper.findProductVoByCreatedId(page, createdById);
    }

    @Override
    public List<ItemVo> findProductList(String productSn) {
        return baseMapper.findProductList(productSn);
    }

    @Override
    public List<Product> findByGoodsId(Long goodsId) {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id", goodsId);
        return list(wrapper);
    }

    @Override
    public List<Product> selectByGoodsIds(Long[] goodsIds) {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.in("goods_id", goodsIds);
        return list(wrapper);
    }

    @Override
    public String test() {
       /* List<Product> productList= productMapper.selectList(new QueryWrapper<Product>().isNotNull("id"));
        for(int i=0;i<productList.size();i++){
            Product product=productList.get(i);
            String goodsSn=product.getGoodsSn();
            String  color=product.getColor();
            String size=product.getSize();
            for(int j=i+1;j<productList.size();j++){
                 Product check=productList.get(j);
                 String checkGoodsn=check.getGoodsSn();
                 String checkColor=check.getColor();
                 String checkSize=check.getSize();
                 if(goodsSn.equals(checkGoodsn)&&color.equals(checkColor)&&size.equals(checkSize)){
                     removeById(check.getId());
                     productList.remove(j);
                     j--;

                 }
            }
        }*/
        List<Product> productList = productMapper.selectList(new QueryWrapper<Product>().eq("product_img", "c8f2d018bf3d47bab88a485553c03a23.jpg"));
        List<GoodsImg> goodsImgList = goodsImgMapper.listAll();
        for (Product product : productList) {
            for (GoodsImg goodsImg : goodsImgList) {
                if (product.getGoodsId().longValue() == goodsImg.getGoodsId().longValue()) {
                    Product product1 = new Product();
                    product1.setId(product.getId());
                    product1.setProductImg(goodsImg.getGoodsImg());
                    updateById(product1);
                    break;
                }
            }
        }

    /*  //  List<Product> productList1=Lists.newArrayList();
        for(int i=0;i<productList.size();i++){
            Product product=productList.get(i);
            String goodsSn=product.getGoodsSn();
            String  color=product.getColor();
            String size=product.getSize();
             for(Product product1:productList1){
                 String checkGoodsn=product1.getGoodsSn();
                 String checkColor=product1.getColor();
                 String checkSize=product1.getSize();
                if(goodsSn.equals(checkGoodsn)&&color.equals(checkColor)&&size.equals(checkSize)){
                  *//*  Product product2=new Product();
                    product2.setId(product1.getId());*//*
                    removeById(product1.getId());

                    break;
                }
            }
        }*/
        /*     updateBatchById(productList1);*/
        return "成功";
    }

    @Override
    public List<ItemVo> getCheckAll() {
        List<ItemVo> itemVoList = baseMapper.getCheckAll();
        for (ItemVo itemVo : itemVoList) {
            if (itemVo.getNumber() >= 2) {
                QueryWrapper<Product> wrapper = new QueryWrapper<>();
                wrapper.eq("goods_id", itemVo.getGoodsId());
                wrapper.eq("color", itemVo.getColor());
                wrapper.eq("size", itemVo.getSize());
                List<Product> productList = list(wrapper);
                for (int i = 0; i < productList.size(); i++) {
                    Product product = productList.get(i);
                    boolean checkOrder = baseMapper.checkOrder(product.getId()) == 0 ? true : false;
                    boolean checkStock = baseMapper.checkStock(product.getId()) == 0 ? true : false;
                    if (checkOrder && checkStock && productList.size() > 1) {
                        baseMapper.deleteById(product.getId());
                        productList.remove(i);
                        i--;
                    }
                }
            }
        }

        return null;
    }

    @Override
    public Map<String, List<SkuVo>> getSkuListByGoodId(Long goodsId) {
        List<SkuVo> productVos = productMapper.selectSkuVoByGoodsId(goodsId);
        Map<String, List<SkuVo>> resultMap = new HashMap<String, List<SkuVo>>();
        List<SkuVo> colorList = Lists.newArrayList();
        List<SkuVo> sizeList = Lists.newArrayList();
        for (SkuVo itemVo : productVos) {
            SkuVo colorSku = new SkuVo();
            SkuVo szieSku = new SkuVo();
            String color = SKUUtils.color2(itemVo.getProductSkuDesp());
            String colorId = SKUUtils.color2(itemVo.getProductSku());
            colorSku.setProductSku(colorId);
            colorSku.setProductSkuDesp(color);
            String size = SKUUtils.size2(itemVo.getProductSkuDesp());
            String sizeId = SKUUtils.size2(itemVo.getProductSku());
            szieSku.setProductSku(sizeId);
            szieSku.setProductSkuDesp(size);
            colorList.add(colorSku);
            sizeList.add(szieSku);
        }
        colorList = colorList.stream().distinct().collect(Collectors.toList());
        sizeList = sizeList.stream().distinct().collect(Collectors.toList());
        resultMap.put("color", colorList);
        resultMap.put("size", sizeList);
        return resultMap;
    }

    @Override
    public List<ItemVo> linshi() {
        List<ItemVo> result = baseMapper.linshi();
        List<ItemVo> collect = result.stream().distinct().collect(Collectors.toList());
        collect = collect.stream().filter(obj -> obj.getNumber() > 1).collect(Collectors.toList());
        for (ItemVo itemVo : collect) {
            List<Product> productList = list(new QueryWrapper<Product>().eq("goods_id", itemVo.getGoodsId()));
            //List<Product> clearList=productList.stream().map(t -> productList.stream().filter(s-> Objects.nonNull(t.getProductSku())&&Objects.nonNull(s.getProductSku())&&Objects.equals(t.getProductSku(),s.getProductSku())).findAny().orElse(null)).filter(Objects::nonNull).collect(Collectors.toList());
            List<Product> clearList = productList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Product::getProductSku))), ArrayList::new));
            for (Product product : productList) {
                boolean tt = check(product, clearList); //返回true说明不需要删除
                if (!tt) {
                    Integer checkOrder = baseMapper.linshi2(product.getId());
                    if (null == checkOrder || checkOrder.equals(0)) {
                        baseMapper.deleteById(product.getId());
                    }
                }
            }

        }
        return null;
    }

    @Override
    public GoodsPlaceVo findGoodsByProductSn(String productSn) {
        return baseMapper.findGoodsByProductSn(productSn);
    }

    /**
     * 初始化图片库
     *
     * @return
     */
    @Override
    public String initImag() {
        List<ItemVo> productList = baseMapper.selectImg();
        List<List<ItemVo>> productList2 = ListUtil.fixedGrouping(productList, 10);
        int index = 0;
        for (List<ItemVo> itemVos : productList2) {
            List<ImgSearchAddDto> imgSearchAddDtos = Lists.newArrayList();
            index++;
            for (ItemVo product : itemVos) {
                ImgSearchAddDto dto = new ImgSearchAddDto();
                dto.setImgUrl(GlobalConstant.IMG_PATH_URL + product.getProductImg());
                dto.setProductId(product.getGoodsId().toString() + "," + product.getId());
                dto.setPicName(product.getGoodsName() + "," + GlobalConstant.IMG_PATH_URL + product.getProductImg());
                dto.setStrAttr(product.getDiscountPrice() + "," + product.getMarketPrice());
                dto.setCustomContent(product.getStyleNo());
                imgSearchAddDtos.add(dto);
            }

            try {
                ImageService imageService = new ImageService();
                boolean result = imageService.add(imgSearchAddDtos, weiXingProperties.getAli().getImg());
                if (result) {
                    for (ItemVo product2 : itemVos) {
                        Product product1 = new Product();
                        product1.setIsLoad(1);
                        update(product1, new UpdateWrapper<Product>().eq("product_img", product2.getProductImg()));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            /*  asyncService.doSomething("index = " + index, imgSearchAddDtos);*/
        }


        return null;
    }

    private boolean check(Product product, List<Product> clearList) {
        for (Product product1 : clearList) {
            if (product1.getId().equals(product.getId())) {
                return true;
            }
        }
        return false;
    }


}
